import sys
import readline
from completer import MyCompleter

class CommandAnalyzer:
    def __init__(self, cl, client):
        self.client = client
        self.cl = cl
        self.aliases =  {
            'bertrandpiquard@gmail.com': 'beb',
            'm.willoquet@gmail.com': 'mat',
            'm.gilot@gmail.com': 'marie',
            'ihsane.moutaib@gmail.com': 'ihsane',
            'charles.rathouis@gmail.com': 'ratwix',
            'benoit.merouze@gmail.com': 'ben',
            'psykocouac@gmail.com': 'jeremy',
            'lecoz.nicolas@gmail.com': 'nico'
        }
        self.online_aliases = {}

        mycompleter = MyCompleter(self.online_aliases)
        readline.set_completer(mycompleter.complete)

    def translate_input(self, str):
        cmd = str.split(":")
        if len(cmd) > 1:
            tojid = cmd[0]
            if not '@' in tojid:
                tojid = self.online_aliases[tojid]
            return "send", (":".join(cmd[1:])).strip(), tojid
        else:
            return "cmd", str.strip(), ""

    def run_cmd(self):
        if self.typ == "send":
            self.client.stdio_message(self.msg, self.jid)
        if self.typ == "cmd":
            if self.msg == 'show':
                self.client.show = 1
                self.client.show_buffered_messages()
            if self.msg == 'hide':
                self.client.show = 0
            if self.msg == 'wohi':
                self.client.show_buffered_messages()
                self.client.show = 0
            if self.msg == 'status':
                if self.client.show:
                    print 'shown'
                else:
                    print 'hidden'
            if self.msg == "quit":
                sys.exit(0)
            if self.msg == "list":
                roster = self.cl.getRoster()
                roster.Request()
                for i in self.online_aliases.keys():
                    del self.online_aliases[i]
                for i in roster.getItems():
                    jid = str(i)
                    name = roster.getName(jid)
                    status = roster.getStatus(jid)
                    show = roster.getShow(jid)
                    resources = roster.getResources(jid)
                    if jid in self.aliases:
                        name = self.aliases[jid]
                    elif not name:
                        name = jid
                    if not show:
                        showd = 'o'
                    elif show == 'away':
                        showd = '*'
                    res = [showd, name, status, "-".join(resources)]
                    res = [i for i in res if i]
                    if resources:
                        print " " + res[0], " ".join(res[1:])
                        self.online_aliases[name] = jid

    def run_once(self, instr):
        self.typ, self.msg, self.jid = self.translate_input(instr)
        self.run_cmd()
